package cn.hy.util;

import cn.hy.entity.ListNode;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class ListNodeUtil {
    /**
     * 返回一个指定长度的随机链表
     * @param size 构造的链表的长度
     * @return 构造好的链表
     */
    public static ListNode constructListNode(int size) {
        ListNode result = new ListNode(-1);
        ListNode pointer = new ListNode(-1, result);
        Random random;

        while (size > 0) {
            random = new Random(System.currentTimeMillis() + size);
            pointer.next.val = random.nextInt(10);

            if (size > 1){
                pointer.next.next = new ListNode(-1);
                pointer.next = pointer.next.next;
            } else if (pointer.next.val == 0){
                pointer.next.val = random.nextInt(9) + 1;
            }
            size--;
        }
        return result;
    }

    /**
     * 根据传入的数组构造一个链表
     * @param listArr 传入的数组
     * @return 构造好的链表
     */
    public static ListNode constructListNode(int[] listArr) {
        if (listArr.length < 1) {
            log.warn("传入的数组为空");
            return new ListNode(-1);
        }
        ListNode result = new ListNode();
        ListNode pointer = new ListNode(-1, result);
        int size = listArr.length-1;
        while (size > 0) {
            pointer.next.val = listArr[size];

            if (size > 1) {
                pointer.next.next = new ListNode();
                pointer.next = pointer.next.next;
            } else if (listArr[size-1] != 0) {
                pointer.next.next = new ListNode();
                pointer.next = pointer.next.next;
                pointer.next.val = listArr[size-1];
            }
            size--;
        }
        return result;
    }

    /**
     * 获取链表的长度
     * @param listNode 待获取长度的链表
     * @return 链表的长度
     */
    public static Integer getLength(ListNode listNode) {
        Integer length = 0;

        while (listNode != null) {
            length++;
            listNode = listNode.next;
        }

        return length;
    }

    /**
     * 将链表转换为字符串
     * @param listNode 待转换的链表
     * @return 转换好的字符串
     */
    public static String toString(ListNode listNode) {
        StringBuilder listNodeString = new StringBuilder();

        while (listNode != null) {
            listNodeString.append(listNode.val);
            listNode = listNode.next;
        }

        return listNodeString.toString();
    }

}
